define(['config', 'text!app/module/system/customer.html', 'laypage',
    'mydialog', 'autocomplete', 'jqGrid', 'common', 'laydate'
], function (config, viewHTML, laypage,
    mydialog, autocomplete, jqGrid, common, laydate) {
	
	var token = (cache.go("token") === 'undefined') ? 'none' : cache.go("token");

    var grid_url = "/api/customer";

    var model = avalon.define({
    	$id : "customer",
    	customerInfo: {

        },
         // 查询条件
         query: {
             fullName: "",
         },

         statusArr: [],
         selected: [],
         roles: [],
         
         init: function () {
             model.loadGrid();
             model.addEvent();
         },
         loadGrid: function () {
             function t(val, opt, row) {
                 var html_con = '<div class="operating" data-id="' + row.id + '"><span class="fa fa-edit mrb" title="修改"><a href="javascript:void();" ms-click="edit(el)"/></span><span class="fa fa-trash-o mrb" title="删除"></span>' + (row.is_deleted == 1 ? '<span class="fa fa-reply mrb" title="恢复"></span>' : '') + '</div>';
                 return html_con;
             }


             var i = Public.setGrid();
             $("#grid").jqGrid({
                 loadBeforeSend: function (jqXHR) {
                     jqXHR.setRequestHeader("X-AuthToken", token);
                 },
                 datatype: "json",
                 mtype: "POST",
                 url: grid_url+"/getlist",
                 postData: model.query.$model,
                 loadComplete: function (data) {},
                 loadError: function (xhr, status, error) {
                     alert(JSON.parse(xhr.responseText).msg);
                 },
                 colModel: [{
                         name: "operating",
                         label: "操作",
                         width: '5%',
                         formatter: t,
                     },
                     {
                         name: "id",
                         label: "编号",
                         width: '4%',
                     },
                     {
                         name: "customerName",
                         label: "客户简称",
                         width: '10%',
                     },
                     {
                         name: "customerFullName",
                         label: "客户全称",
                         width: '13%',
                     },
                     {
                         name: "contact",
                         label: "联系人",
                         width: '10%',
                     },
                     {
                         name: "email",
                         label: "邮箱",
                         width: '10%',
                     },
                     {
                         name: "telNo",
                         label: "联系电话",
                         width: "7%"
                     },
                     {
                         name: "shipAdd",
                         label: "收货人地址",
                         width: '13%',
                     },
                     {
                         name: "billAdd",
                         label: "账单地址",
                         width: '13%',
                     },
                     {
                         name: "sendInvoiceAdd",
                         label: "发票地址",
                         width: '13%',
                     },
                     {
                         name: "emsNo",
                         label: "账单号",
                         width: '13%',
                     },
                     {
                         name: "invoiceNo",
                         label: "发票号",
                         width: '13%',
                     }
                 ],
                 cmTemplate: {
                     sortable: false,
                     title: false,
                     align: "center"
                 },
                 //分页
                 page: 1,
                 rowNum: 10,
                 rowList: [10, 20, 30],
                 height: i.h,
                 autowidth: true,
                 pager: '#page',
                 sortname: 'id',
                 viewrecords: true,
                 forceFit: false,
                 rownumbers: true,
                 multiselect: true,
                 multiboxonly: true,
                 sortorder: "desc",
                 jsonReader: {
                     root: "data.list",
                     records: "data.totalRow",
                     total: "data.totalPage",
                     repeatitems: false,
                     id: "id"
                 },
                 loadError: function () {
                     parent.Public.tips({
                         type: 1,
                         content: "加载数据异常！"
                     })
                 }
             })
         },
         reset: function () {
             model.query = {
                 fullName: ""
             };
             model.queryData();
         },
         queryData: function () {
//             debugger;
             $("#grid").jqGrid("setGridParam", {
                 url: grid_url+"/getlist",
                 datatype: "json",
                 mtype: 'POST',
                 page:1,
                 postData: model.query.$model
             }).trigger("reloadGrid");
         },
         
         
         //添加或更新
         edit: function (customerInfo) {
        	 console.log(customerInfo);
             if (customerInfo === -1) {
                 // 创建用户
                 model.initcustomer();
           
                 url = "/api/customer/save";
             } else {
                 // 修改用户
                 model.customerInfo = customerInfo;
                 
                 url = "/api/customer/save";

             }
             dialog({
                 title: '编辑客户信息',
                 content: $('#editUser'),
                 okValue: "确定",
                 ok: function () {
                     // 提交修改
                    if(model.isEmpty(model.customerInfo.customerName.trim(),"客户简称不能为空!") && model.isEmpty(model.customerInfo.customerFullName.trim(),"客户全称不能为空!") && model.isEmpty(model.customerInfo.billAdd.trim(),"账单地址不能为空!") && model.isEmpty(model.customerInfo.sendInvoiceAdd.trim(),"发票地址不能为空!") && model.isEmpty(model.customerInfo.emsNo.trim(),"账单号不能为空!") && model.isEmpty(model.customerInfo.invoiceNo.trim(),"发票号不能为空!")){
                         $.ajax({
                             type: "POST",
                             url: url,
                             contentType: "application/json",
                             data: JSON.stringify(model.customerInfo.$model),
                             beforeSend: function (xhr) {
                                 xhr.setRequestHeader("X-AuthToken", token);
                             },
                             success: function (data, status, xhr) {
                                 model.queryData();
                             },
	                             error: function (responseData, textStatus, errorThrown) {
                                 alert("系统异常");
                             }
                         });
                    }
                    else {
                        return false;
                    }
                 },
                 cancelValue: "取消",
                 cancel: function () {}
             }).showModal();
         },
         del: function (ids) {
             dialog({
                 title: "确认操作",
                 content: "确定删除？ 此操作不可恢复！",
                 okValue: "确定",
                 ok: function () {

                     $.ajax({
                         type: "POST",
                         url: "/api/customer/delete",
                         data: {
                             "ids": ids
                         },
                         beforeSend: function (xhr) {
                             xhr.setRequestHeader("X-AuthToken", token);
                         },
                         success: function (data, status, xhr) {
                             if (data) {
                                 $('#grid').jqGrid('delRowData', ids);
                             }
                             model.queryData();
                         },
                         error: function (responseData, textStatus, errorThrown) {
                             alert("Failed: " + responseData);
                         }

                     });

                 },
                 cancelValue: "取消",
                 cancel: function () {}
             }).showModal();
         },
        isEmpty: function (value, alerttxt) {
            if (value == null || value == "") {
                Public.tips({
                    type: 2,
                    content: alerttxt
                });
                return false;
            }
            else {
                return true;
            }
        },		 
         addEvent: function () {
             var t = this;
             $(".grid-wrap").on("click", ".fa-edit", function (e) {
                 var t = $(this).parent().data("id");
                 model.edit($("#grid").getRowData(t));
             });
             // 删除
             $(".grid-wrap").on("click", ".fa-trash-o", function (t) {
                 var ei = [];
                 var e = $(this).parent().data("id");
                 ei.push(e);
                 model.del(e);
             });
             $("#search").click(function (e) {
                 e.preventDefault();
                 model.queryData();
             });
             $(".fa-refresh").click(function (e) {
                 e.preventDefault();
                 model.reset();
                 model.queryData();
             })
             //编辑用户信息
             $(".grid-wrap").on("click", ".userManage", function (e) {
                 var id = $("#grid").jqGrid('getGridParam', 'selrow'),
                     userId = $("#grid").jqGrid("getRowData", id).userId;
                 model.editUser(userId);
             })
             $(".grid-wrap").on("click", ".userRole", function (e) {
                 var id = $("#grid").jqGrid('getGridParam', 'selrow'),
                     userId = $("#grid").jqGrid("getRowData", id).userId;
                 model.editUserRole(userId);
             })
            
//             $("#aadddd").click(function (t) {
//                 model.edit(-1);
//             });
             $("#btn-batchDel").click(function (e) {
                 e.preventDefault();
                 // if (Business.verifyRight("BU_DELETE")) {
                 var t = $("#grid").jqGrid("getGridParam", "selarrrow");
                 console.log('[t]',t);
                 t.length ? model.del(t.join()) : parent.Public.tips({
                     type: 2,
                     content: "请选择需要删除的项"
                 })
                 // }
             });
         },
         initcustomer: function () {
             model.customerInfo = {
                     id: "",
                     contact: "",
                     email: "",
                     telNo: "",
                     telNo: "",
                     customerName: "",
                     customerFullName: "",
                     shipAdd: "",
                     billAdd: "",
                     sendInvoiceAdd: "",
                     emsNo: "",
                     invoiceNo: ""
                 }
             }
    });
    
    // 定义视图模块
    var viewmod = {
        viewtSrc: viewHTML,
        viewInit: function () {
            model.init();
        }, // 模块view加载完成后的回调方法，在刷新（F5）时可能调用两次
        viewDestroy: function () {} // 切换菜单时销毁原来的view
    };
    return viewmod;
	
	
});
